<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/6
 * Time: 10:47
 */

namespace App\Http\Controllers\Api\V5;

use App\Common\ApiData;
use App\Models\V1\LiveModel;
use App\Modules\EntMemberDRP;
use Illuminate\Http\Request;
use Validator;

use App\Models\V5\BookSentenceModel;
use App\Models\V5\MemberModel;
use App\Models\V5\BookModel;
use App\Models\V5\ArticleModel;
use App\Models\V5\AudioModel;
use DB;
use App\Models\V5\BannersModel;


class HomeController extends BaseController
{
    protected $url;

    public function __construct()
    {
        $this->url = env('ADMIN_HOST');
    }


    /**
     * 首页接口
     *
     */
    public function home(Request $request)
    {
        $appKey    = $request->input('appKey');
        //1.直播信息
        $condition = [
            'is_end'        => 0,
            'is_completed'  => 1,
            'is_show'       => 1
        ];

        $colum = [
            'live_title',
            'description',
            'id',
            'live_type',
            'begin_time',
            'live_status'
        ];

        $live_info   = LiveModel::where($condition)->select($colum)->orderBy('id', 'desc')->first();
        $memberModel = new MemberModel();
        $userId      = $request->input('tokenUserId',0);
        $memberInfo  = $userId > 0 ? $memberModel->get_member_info_by_id($userId) : false;

        if ($live_info) {//有直播

            if ($live_info->live_type == 1) {
                if ($memberInfo && $memberInfo->isValid) {//用户是有效的
                    $memnumber           = $memberInfo->MemNumber;
                    $level               = EntMemberDRP::where('MemNumber', $memnumber)->select('DRPLevel')->first();//判断用户是否是学习官
                    $live_info->is_watch = ($level && $level->DRPLevel == 1) ? 1 : 0;
                } else {//用户无效
                    $live_info->is_watch = 0;
                }
            } else {//用户不是学习官
                $live_info->is_watch = 1;
            }
            //判断是否正在直播
            $live_info->is_live_now = $live_info->live_status == 1 ? 1 : 0;
        }

        unset($live_info->live_status);

        /*2.老侯论道音频*/
        $audioModel = new AudioModel();
        $audioList  = $audioModel->get_audio_list($userId);

        foreach ($audioList as $audio) {
            $params = [
                'audioId'  => $audio->AudioID,
                'parentId' => 0
            ];
            $params = http_build_query($params);

            $shareInfo        = [
                'title'       => "老侯论道",
                'groupTitle'  => $audio->AudioTitle,
                'description' => $audio->AudioTitle,
                'img'         => env('ADMIN_HOST') . "/images/default-images/share-mp3.png",
                'link'        => env('ADMIN_HOST') . "/home/audio_share_to_weixin?" . $params,
                "audio"       => $audio->FilePath1,
            ];
            $audio->shareInfo = $shareInfo;
        }



        /*3.免费书籍*/
        $bookModel = new BookModel();
        $freeBook   = $bookModel->get_book_list(0,'',1);
        $books      = [];
        foreach($freeBook as $key => $book)
        {
            if($key > 2)
            {
                break;
            }
            $book->bg_img       = env('HOST')."/".$book->bg_img;
            $book->ReadNumber   = change_read_number($book->ReadNumber);
            array_push($books,$book);
        }


        /*4.言图*/
        $bookSentenceModel      = new BookSentenceModel();
        $date                   = current_date();
        $bookSentence           = $bookSentenceModel->get_day_sentence($date);
        $thumbImg               =  $bookSentence->bg_img;
        $thumbFile              = dirname($thumbImg)."/".$bookSentence->id.".jpg";
        $bookSentence->bg_img   = env('HOST') . "/" . $bookSentence->bg_img;
        $bookSentence->thumb_img= env('HOST') . "/" . $thumbFile."?x";

        //检查是否有缩略图  没有则生成
        if(!file_exists($thumbFile))
        {
            $scale      = 5;
            $width      = 1080 - (31*2);//60 * $scale;
            $height     = $width * (5/6);// * $scale;
            $thWidth    = $width / $scale;
            $thHeight   = $height / $scale;
            $dstImg     = imagecreatetruecolor($thWidth,$thHeight);
            $imgSource  = imagecreatefromjpeg($bookSentence->bg_img);;
            //imagecopy($dstImg,$imgSource,0,0,31,35,$width,$height);
            imagecopyresized($dstImg,$imgSource,0,0,31,35,$thWidth,$thHeight,$width,$height);
            imagejpeg($dstImg,$thumbFile);
        }

        /*5.登录背景图片*/
        $loginBgImg     = env('HOST') . system_log('login_bg_img');//登录背景图片


        /*6.banner图片*/
        $bannersModel   = new BannersModel();
        $banners        = $bannersModel->get_banners('appindex');
        foreach($banners as $banner)
        {
            $banner->img = env('HOST').$banner->img;
        }

        //7.老侯论道音频上面的图片
        $lundaoImg  = env('HOST')."/images/uploads/2018/2/lundao2.jpg";
        $lundaoInfo = [
            'lundaoImg' => $lundaoImg,
            'bigTitle'  => '老侯论道',
            'subTile'=> '与你一起坐而论道'
        ];

        if($userId > 0)
        {
            $memStatus  = get_user_status(true,$memberInfo->States,$memberInfo->MemEndTime,$appKey);
        }else{

            $memStatus  = get_user_status(false);
        }

        $payType    = 0;//支付的三种类型 0：不打开支付，1：内部支付，2：微信支付

        return apiData()
            ->set_data('memstate',$memStatus)
            ->set_data('payType',$payType)
            ->set_data('lundaoInfo',$lundaoInfo)
            ->set_data('loginBgImg', $loginBgImg)
            ->set_data('lundaoList', $audioList)
            ->set_data('freeBooks', $books)
            ->set_data('liveInfo', $live_info)
            ->set_data('banners',  $banners)
            ->set_data('bookSentence', $bookSentence)
            ->send(200, 'ok');
    }


    /**
     * 媒体播放日志
     * */
    public function media_play_log(Request $request)
    {
        $medias      = $request->input('medias');
        $medias      = \GuzzleHttp\json_decode($medias);
        $userId      = $request->input('userId');
        $time        = date_time();
        $memberModel = new MemberModel();

        $types = [
            "lhddmp4" => "看老侯代读视频",
            "lhddmp3" => "听老侯代读音频",
            "gzsbmp4" => "看国政书吧视频"
        ];

        foreach ($medias as $media) {
            $data = [
                'media_id'   => $media->media_id,
                'media_type' => $media->media_type,
                'user_id'    => $userId,
                'begin_time' => date_time($media->begin_time),
                'end_time'   => date_time($media->end_time),
                'created_at' => $time,
                'updated_at' => $time
            ];
            DB::table('media_play_log')->insert($data);

            //计算积分  每看视频10分钟加三分
            $minute     = round(($media->end_time - $media->begin_time) / 60);
            $tenMinutes = $minute / 1;
            $integral   = $tenMinutes * 1;
            $note       = $types[$media->media_type] . $minute . "分钟";
            $memberModel->add_member_integral($userId, $integral, $media->media_id, $note);
        }

        return apiData()->send(200, 'ok');
    }


    /**
     * 记录微信分享日志
     * */
    public function wx_share_log(Request $request)
    {
        $shareContent = [
            'index1' => [5, '老侯论道分享'],
            'index2' => [5, '言图分享'],
            'index3' => [5, '自学习社群文章'],
            'index4' => [5, '自己的读书改进计划'],
            'index5' => [5, '听代读签到']
        ];

        $index     = "index" . $request->input('contentType');
        $info      = $shareContent[$index];
        $userId    = $request->input('userId');
        $contentId = $request->input('contentId');
        $integral  = $info[0];
        $note      = $info[1];

        $memberModel = new MemberModel();
        $memberModel->add_member_integral($userId, $integral, $contentId, $note);

        return apiData()->send(200, 'ok');
    }


}